<?php
class ControllerCatalogDownload extends AdminController {

  	public function index() {
		M('catalog/download');
		$this->getList();
  	}

  	public function insert() {
		M('catalog/download');

		if ($this->request->isPost() && $this->validateForm()) {
			$this->model_catalog_download->addDownload($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/download'));
		}
    	$this->getForm();
  	}

  	public function update() {
		M('catalog/download');

    	if ($this->request->isPost() && $this->validateForm()) {
			//delete old file
			$download = $this->model_catalog_download->getDownload(G('download_id'));
			if ($download['filename'] !== P('filename')
				&& file_exists(DIR_DOWNLOAD . $download['filename'])) {
					unlink(DIR_DOWNLOAD . $download['filename']);
			}
			
			$this->model_catalog_download->editDownload(G('download_id'), $this->request->post);
			
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/download'));
		}

    	$this->getForm();
  	}

  	public function delete() {
		M('catalog/download');

    	if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $download_id) {
				//delete file
				$download = $this->model_catalog_download->getDownload($download_id);
				if (file_exists(DIR_DOWNLOAD . $download['filename'])) {
					unlink(DIR_DOWNLOAD . $download['filename']);
				}
				$this->model_catalog_download->deleteDownload($download_id);
			}

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('catalog/download'));
    	}
    	$this->getList();
  	}

  	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);

		$qf = new  Query_filter();

		$download_total = $this->model_catalog_download->getTotalDownloads($qf);
		$this->data['downloads'] = $this->model_catalog_download->getDownloads($qf);

		$this->data['pagination'] = $this->pagination($download_total)->render();

		$this->display('catalog/download_list.tpl');
  	}

  	protected function getForm() {
		$this->document->setTitle($this->_['heading_title']);

		$download_id = $this->request->get('download_id', 0);

		if ($download_id) {
			$this->data['action'] = UA('catalog/download/update', 'download_id=' . $download_id);
	    	if (!$this->request->isPost()) {
				$this->vo->data = $this->model_catalog_download->getDownload($download_id);
				$this->vo->data['download_description'] = $this->model_catalog_download->getDownloadDescriptions($download_id);
	    	}
		} else {
			$this->data['action'] = UA('catalog/download/insert');
		}

		$this->data['languages'] = C('cache_language_2');

		$this->display('catalog/download_form.tpl');
  	}

  	protected function validateForm() {
		$this->load->library('form_validation', true);
    	foreach ($this->request->post['download_description'] as $language_id => $value) {
			$this->form_validation->set_rules("download_description[$language_id][name]", '', 'required|range_length[3,64]', $this->_['error_name']);
    	}

		$this->form_validation->set_rules("filename", '', 'required|range_length[3,128]', $this->_['error_filename']);

		$this->form_validation->set_rules("mask", '', 'required|range_length[3,128]', $this->_['error_mask']);

		if ($this->form_validation->run()) {
			if (!file_exists(DIR_DOWNLOAD . $this->request->post['filename']) && !is_file(DIR_DOWNLOAD . $this->request->post['filename'])) {
				$this->form_validation->set_error('filename', $this->_['error_exists']);
				return false;
			}
			return true;
		}
		else return false;
  	}

  	protected function validateDelete() {

		M('catalog/product');
		foreach ($this->request->post['selected'] as $download_id) {
  			$product_total = $this->model_catalog_product->getTotalProductsByDownloadId($download_id);

			if ($product_total) {
	  			$this->setMessage('error_warning', sprintf($this->_['error_product'], $product_total));
				return false;
			}
		}
		return true;
  	}

	public function upload() {
		$this->language->load('sale/order');

		$json = array();

		if (!$this->hasMP()) {
      		$json['error'] = $this->_['error_permission'];
    	}

		if (!isset($json['error'])) {
			if (!empty($this->request->files['file']['name'])) {
				$filename = basename(v5_html_entity_decode($this->request->files['file']['name']));

				if (!range_length($filename, 3, 128)) {
					$json['error'] = $this->_['error_filename'];
				}

				// Allowed file extension types
				$allowed = array();

				$filetypes = explode(",", C('config_file_extension_allowed'));
				foreach ($filetypes as $filetype) {
					$allowed[] = trim($filetype);
				}

				if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
					$json['error'] = $this->_['error_filetype'];
				}

				// Allowed file mime types
				$allowed = array();

				$filetypes = explode("\n", C('config_file_mime_allowed'));
				foreach ($filetypes as $filetype) {
					$allowed[] = trim($filetype);
				}

				if (!in_array($this->request->files['file']['type'], $allowed)) {
					$json['error'] = $this->_['error_filetype'];
				}

				if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
					$json['error'] = $this->_['error_upload_' . $this->request->files['file']['error']];
				}
			} else {
				$json['error'] = $this->_['error_upload'];
			}
		}

		if (!isset($json['error'])) {
			if (is_uploaded_file($this->request->files['file']['tmp_name'])
					&& file_exists($this->request->files['file']['tmp_name'])) {
				$ext = md5(mt_rand());

				$json['filename'] = $filename . '.' . $ext;
				$json['mask'] = $filename;

				move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
			}

			$json['success'] = $this->_['text_upload'];
		}

		$this->response->setOutput(json_encode($json));
	}

	public function autocomplete() {
		$json = array();

		if (isset($this->request->get['filter_name'])) {
			M('catalog/download');

			$results = $this->model_catalog_download->getDownloads(new Query_filter(null, false));

			foreach ($results as $result) {
				$json[] = array(
					'download_id' => $result['download_id'],
					'name'        => strip_tags(v5_html_entity_decode($result['name']))
				);
			}
		}

		$this->response->setOutput(json_encode($json));
	}
}
?>